import React, { useState, useEffect } from 'react';
import { Table, Typography, Card, Button, Tag, Space, Alert, Spin } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { ollamaService, ModelInfo } from '../services/ollamaService';

const { Title, Text } = Typography;

export default function ModelsPage() {
  const [models, setModels] = useState<ModelInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchModels();
  }, []);

  const fetchModels = async () => {
    setLoading(true);
    setError(null);
    try {
      const modelList = await ollamaService.getModels();
      setModels(modelList);
    } catch (err) {
      setError('获取模型失败。请检查您的Ollama服务器连接。');
      console.error('获取模型错误:', err);
    } finally {
      setLoading(false);
    }
  };

  const formatSize = (sizeInBytes: number) => {
    if (sizeInBytes < 1024) return `${sizeInBytes} B`;
    const sizeInKB = sizeInBytes / 1024;
    if (sizeInKB < 1024) return `${sizeInKB.toFixed(2)} KB`;
    const sizeInMB = sizeInKB / 1024;
    if (sizeInMB < 1024) return `${sizeInMB.toFixed(2)} MB`;
    const sizeInGB = sizeInMB / 1024;
    return `${sizeInGB.toFixed(2)} GB`;
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString();
  };

  const columns = [
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      render: (size: number) => formatSize(size),
    },
    {
      title: '最后修改',
      dataIndex: 'modified_at',
      key: 'modified_at',
      render: (date: string) => formatDate(date),
    },
    {
      title: '摘要',
      dataIndex: 'digest',
      key: 'digest',
      render: (digest: string) => <Text ellipsis style={{ maxWidth: 150 }}>{digest}</Text>,
    },
  ];

  return (
    <div style={{ maxWidth: 1000, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <Title level={2}>可用模型</Title>
        <Button 
          type="primary" 
          icon={<ReloadOutlined />} 
          onClick={fetchModels}
          loading={loading}
        >
          刷新
        </Button>
      </div>

      {error && (
        <Alert 
          message="错误" 
          description={error} 
          type="error" 
          showIcon 
          closable 
          onClose={() => setError(null)} 
          style={{ marginBottom: 20 }}
        />
      )}

      {loading && !error && (
        <div style={{ textAlign: 'center', margin: '40px 0' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text>正在加载模型...</Text>
          </div>
        </div>
      )}

      {!loading && !error && models.length === 0 && (
        <Card>
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Text style={{ fontSize: 16 }}>
              未找到模型。请确保您的Ollama服务器正在运行并已安装模型。
            </Text>
          </div>
        </Card>
      )}

      {models.length > 0 && (
        <Card>
          <Table 
            dataSource={models} 
            columns={columns} 
            rowKey="name"
            pagination={false}
          />
        </Card>
      )}
    </div>
  );
} 